package com.math.aistudykbr.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.math.aistudykbr.exception.QuestionParseException;
import com.math.aistudykbr.mapper.QAMapper;
import com.math.aistudykbr.pojo.entity.ChoiceQuestion;
import com.math.aistudykbr.pojo.entity.LearningMaterial;
import com.math.aistudykbr.service.AIService;
import com.math.aistudykbr.service.IQAService;
import com.math.aistudykbr.utils.UserContext;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class QAServiceImpl implements IQAService {

    private final AIService aiService;

    private final QAMapper qaMapper;

    // 新增：解析结果类
    @Getter
    @AllArgsConstructor
    private static class ParseResult {
        private final List<ChoiceQuestion> questions;
        private final int totalAttempted;
        private final List<String> errors;
    }

    @Override
    public List<ChoiceQuestion> generateQuestions(Long materialId, Integer count) {
        // 1. 获取学习资料内容
        LearningMaterial material = qaMapper.getMaterialById(materialId);
        if (material == null) {
            throw new RuntimeException("学习资料不存在");
        }

        // 2. 构建AI提示语
        String prompt = String.format(
                "严格按照模板，不要有其他字符。请基于以下学习内容，生成%d道选择题。每道题必须包含：\n" +
                        "1. 题目内容\n" +
                        "2. 四个选项(A、B、C、D)\n" +
                        "3. 正确答案\n" +
                        "4. 详细解析\n" +
                        "5. 难度等级(1-简单，2-中等，3-困难)\n\n" +
                        "请按照以下格式返回：\n" +
                        "题目1：\n问题内容\nA. 选项A\nB. 选项B\nC. 选项C\nD. 选项D\n正确答案：X\n解析：xxx\n难度：x\n\n" +
                        "学习内容：\n%s",
                count, material.getContent());

        // 3. 调用AI生成题目
        String response;
        try {
            response = aiService.chatWithAI(UserContext.getUser(), prompt);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("AI生成题目失败", e);
        }

        // 4. 解析AI响应，转换为题目对象并保存
        log.info("AI生成题目响应: {}", response);
        ParseResult parseResult = parseAIResponse(response, materialId);

        // 5. 记录解析结果
        if (!parseResult.errors.isEmpty()) {
            log.warn("题目解析出现{}个错误: {}", parseResult.errors.size(), parseResult.errors);
        }

        // 6. 保存成功解析的题目
        for (ChoiceQuestion question : parseResult.questions) {
            qaMapper.saveQuestion(question);
        }

        return parseResult.questions;
    }

    @Override
    public List<ChoiceQuestion> getQuestionsByMaterialId(Long materialId) {
        return qaMapper.getQuestionsByMaterial(materialId);
    }

//    @Override
//    public Boolean submitAnswer(Long userId, Long questionId, String answer) {
//        // 1. 获取题目
//        ChoiceQuestion question = qaMapper.getQuestionById(questionId);
//        if (question == null) {
//            throw new RuntimeException("题目不存在");
//        }
//
//        // 2. 判断答案是否正确
//        boolean isCorrect = question.getCorrectAnswer().equalsIgnoreCase(answer);
//
//        // 3. 保存答题记录
//        UserAnswer userAnswer = UserAnswer.builder()
//                .userId(userId)
//                .questionId(questionId)
//                .userAnswer(answer)
//                .isCorrect(isCorrect)
//                .build();
//        qaMapper.saveUserAnswer(userAnswer);
//
//        return isCorrect;
//    }

    private ParseResult parseAIResponse(String response, Long materialId) {
        List<ChoiceQuestion> questions = new ArrayList<>();
        List<String> errors = new ArrayList<>();

        // 使用正则表达式匹配题目
        String[] questionTexts = response.split("(?m)^题目\\d+：\\s*$");
        int totalAttempted = questionTexts.length;

        for (String questionText : questionTexts) {
            try {
                if (questionText.trim().isEmpty())
                    continue;

                String[] parts = questionText.split("\n");
                ChoiceQuestion question = new ChoiceQuestion();
                question.setMaterialId(materialId);

                for (String part : parts) {
                    part = part.trim();
                    try {
                        parseQuestionPart(part, question);
                    } catch (QuestionParseException e) {
                        errors.add(String.format("题目解析错误: %s, 字段: %s", e.getMessage(), e.getField()));
                        continue;
                    }
                }

                if (isValidQuestion(question)) {
                    questions.add(question);
                } else {
                    errors.add("题目数据不完整: " + questionText);
                }
            } catch (Exception e) {
                errors.add("题目解析异常: " + e.getMessage());
                log.error("解析题目失败", e);
            }
        }

        return new ParseResult(questions, totalAttempted, errors);
    }

    private void parseQuestionPart(String part, ChoiceQuestion question) {
        if (part.startsWith("A.")) {
            question.setOptionA(part.substring(2).trim());
        } else if (part.startsWith("B.")) {
            question.setOptionB(part.substring(2).trim());
        } else if (part.startsWith("C.")) {
            question.setOptionC(part.substring(2).trim());
        } else if (part.startsWith("D.")) {
            question.setOptionD(part.substring(2).trim());
        } else if (part.startsWith("正确答案：")) {
            String answer = part.substring(5).trim();
            if (!isValidAnswer(answer)) {
                throw new QuestionParseException("无效的答案格式", part, "correctAnswer");
            }
            question.setCorrectAnswer(answer);
        } else if (part.startsWith("解析：")) {
            question.setExplanation(part.substring(3).trim());
        } else if (part.startsWith("难度：")) {
            Integer level = parseDifficultyLevel(part.substring(3).trim());
            if (level == null) {
                throw new QuestionParseException("无效的难度级别", part, "difficultyLevel");
            }
            question.setDifficultyLevel(level);
        } else if (question.getQuestionContent() == null && 
                  !part.trim().isEmpty() && 
                  !part.startsWith("题目")) {
            // 直接设置问题内容，确保不为空且不是题目编号
            question.setQuestionContent(part);
        }
    }

    private boolean isValidAnswer(String answer) {
        return answer != null && answer.matches("[A-D]");
    }

    private Integer parseDifficultyLevel(String level) {
        try {
            int difficulty = Integer.parseInt(level);
            return (difficulty >= 1 && difficulty <= 3) ? difficulty : null;
        } catch (NumberFormatException e) {
            return null;
        }
    }

    private boolean isValidQuestion(ChoiceQuestion question) {
        return question.getQuestionContent() != null &&
                question.getOptionA() != null &&
                question.getOptionB() != null &&
                question.getOptionC() != null &&
                question.getOptionD() != null &&
                question.getCorrectAnswer() != null &&
                question.getExplanation() != null &&
                question.getDifficultyLevel() != null;
    }

    @Override
    @Transactional
    public Map<Long, Boolean> submitAnswersBatch(Long userId, Map<Long, String> answers, Long materialId) {
        Map<Long, Boolean> results = new HashMap<>();
        
        // 一次性获取所有题目
        List<ChoiceQuestion> questions = qaMapper.getQuestionsByMaterial(materialId);
        // 将题目列表转换为Map，方便查找
        Map<Long, ChoiceQuestion> questionMap = questions.stream()
                .collect(Collectors.toMap(ChoiceQuestion::getId, q -> q));
        log.info("题目数量: {}", questionMap.size());
    
        for (Map.Entry<Long, String> entry : answers.entrySet()) {
            Long questionId = entry.getKey();
            String userAnswer = entry.getValue();
            log.info("用户提交的答案: {} - {}", questionId, userAnswer);
            
            // 从Map中获取题目信息
            ChoiceQuestion question = questionMap.get(questionId);
            if (question == null) {
                continue;
            }
            
            // 判断答案是否正确
            boolean isCorrect = question.getCorrectAnswer().equalsIgnoreCase(userAnswer);

            // 保存答题记录
            qaMapper.updateQuestionAnswer(materialId, questionId, userAnswer, isCorrect ? 1 : 0);
            
            // 记录结果
            results.put(questionId, isCorrect);
        }
        // TODO: 考虑添加错题集功能
        
        return results;
    }
}
